Method and computer programming product for detecting memory leaks

ABSTRACT

The invention relates to a method for detecting memory leaks produced by a program running on a computer, wherein during a program run, for each allocation of a memory region at least one information item concerning the performed allocation is entered in an allocation list and a check is made as to whether the allocation list contains a stored reference pattern of information that is typical for one or more memory leaks, and after a stored reference pattern is found the program run is paused, or a memory leak thus detected is associated with the region of the running program whose processing resulted in the most recent entry in the allocation list. The invention further relates to a computer programming product which carries out the method when the computer program is executed on a computer.

RELATED APPLICATION(S)

This application is a continuation application of co-pending applicationSer. No. 11/765,911 filed on Jun. 20, 2007, which claims priority under35 USC §119 to German Application No. 10 2006 029 138.7 filed Jun. 22,2006 incorporated herein by reference.

FIELD OF THE INVENTION

The present invention relates to a method and a computer programmingproduct for detecting memory leaks produced by a program running on acomputer, where a memory leak list is generated while the program isrunning.

BACKGROUND

A memory leak refers to an allocated memory region, a memory block, forexample, which, after being used by a program running on a computer, isnot released. For the entire run time of the program, this memoryregion, in particular memory block, can then no longer be used for theprogram or for other purposes (other programs or operating systemrequirements), so that the free memory still available may run low,particularly when such memory leaks occur numerous times.

In addition, as the result of fragmentation of the main memory due tounreleased memory regions it may no longer be possible for the system toeffectively access large contiguous memory blocks (larger than 100 MB,for example). The system may be burdened and may become progressivelymore unstable.

For programmers, such memory management errors occur relativelyfrequently in computer-based languages (such as C/C++). Due to theever-increasing complexity, the programmer forgets to release thereserved memory region/memory block at the correct time. A detaileddiscussion of the fundamentals of memory leaks is disclosed in US2005/0235127 A1 and US 2004/0078540 A1, for example.

By use of automated software it is practically impossible to determinethe point in time after which a memory region/memory block is no longerbeing used by a program. There is currently no tool which allows thedeveloper to identify 100% of such cases. Although the developer canobtain a list of all memory leaks that have occurred after the programhas ended, as described below, in order to eliminate the underlyingprogramming error the developer would require an association with thespecific situation during the program execution in which the memoryregion/memory block in question is allocated.

Commercially available tools, such as the FindLeak program by cjtSystemsoftware AG and the methods described in US 2005/0235127 A1 and US2004/0078540 A1, give the developer a heuristic method-based indicationof potential memory leaks. A disadvantage is that the developer mustconstantly verify the individual memory leaks; i.e., it is not clearthat all unreleased memory region/memory blocks are memory leaks untilthe program has ended. No option is provided for associating theconfirmed memory leaks at the end of the program with the heuristicinformation, and thus there is no option for tracking more detailedinformation about the memory leak when the program is running.

To reduce the described problems, with CRT (C run-time) library and MFC(Microsoft Foundation Classes) Microsoft Visual Studio offers thedeveloper the option of labeling potential memory leaks after a programhas run. To this end, MFC logs all memory allocations and deallocations,and after the program has run, indicates all remaining entries as textoutput, for example, in a debug output window in the form of a memoryleak list or memory leak dump. Thus, by use of this option offered byMicrosoft or other providers the programmer may generate a memory leaklist in which all memory regions/memory blocks that are allocated but nolonger released are listed, optionally together with other information.

An MFC application generated in Visual Studio using wizard supportautomatically logs and reports the memory requirements. Inself-generated configurations, the developer may start the log processusing the _CrtSetDbgFlag method.

The information which MFC is able to provide at this point in time isrudimentary. Class names or call stacks are no longer available afterthe program has ended, and logging of this information during the runtime is very memory-intensive. The file name and the line number inwhich the object is allocated is sometimes given, but frequently thisinformation is not provided, since the name of the file from which therequest comes is not known unless the name has been specificallydelivered to the logging memory management routines, which often doesnot occur. Preprocessor macros are used for this purpose, but suchmacros are prone to malfunction, if they can be used at all. Thus, as arule only about 50% of memory leaks are provided with file names.

Although the file name and line number give a precise indication of theobject that has been allocated, in most cases this is not useful to thedeveloper, since the allocation code is generally satisfactory and theprogrammer must determine why the object is being allocated and notreleased, and in particular, at what location in a program this errorhas occurred.

The memory address contains little useful information since it changeswith each program run, and after the program has run the memory addressprovides no information concerning the context of the allocation.

Under special circumstances the memory block size gives the developerinformation about the object, but generally is not predictive andtherefore is not used in standard methods. In addition, the experienceof the developer is a factor that determines the usefulness of thisinformation.

The core concept of a method proposed by Microsoft for eliminatingmemory leaks is the introduction of a consecutive allocation numberwhich indicates order number of the memory allocation during the programrun which has resulted in the memory leak.

Together with the referenced logging option, there is, for example, thefunction (_CrtSetBreakAlloc) by means of which the developer mayinterrupt execution of the program when an allocation number deliveredto the function has been reached. If the developer provides the numberreported at the last memory leak dump to said function, the programpauses at the next run exactly at the location where the “lost” objectis allocated. This association of the identified memory leak with thespecific run time situation during the allocation gives the developercrucial information for eliminating the underlying programming error.

For large GUI-intensive applications, however, in actual practiceallocation numbers are in the 6 to 8 digit range for most memory leaks.Due to the intense networking of these applications with the autonomousGUI and task management of the operating system, the linkage between theobject allocation and the allocation number is no longer deterministic.Even small differences in run time between two program runs intended tobe identical result in unpredictable shifts in the allocation numbersfor the same object in the various runs.

This may be due to the fact that, for example, in addition to theallocations of memory regions by the program to be investigated, theoperating system or other programs running in parallel also performallocations of memory regions. This results in intermingling of thememory allocations and possibly of the releases of the program that isto be investigated with the allocations and possibly releases of otherprograms or the operating system. This makes it virtually impossible fora programmer to draw conclusions concerning the reason for anallocation, and in particular, the lack of a deallocation.

The method proposed by Microsoft reaches its natural limit at thispoint. Because of the difficulty in determining the circumstances ofallocation and release, the allocation number loses its informativevalue, and it is therefore impossible to search for the underlyingprogramming error for the memory leak.

SUMMARY

One object of the present invention is to provide a method and acomputer programming product by means of which memory leaks resultingfrom programming error in a running program may be detected withcertainty, or at least with greater probability, and which enablesprogramming regions responsible for creating memory leaks to be assignedto corresponding memory leaks.

A further object is to eliminate the described disadvantages of theprior art, and, despite the indeterminability, in particular of theallocation numbers, to identify the causes of the memory leaks, i.e., toobtain information concerning the program location in a running programwhich is causing the memory leak.

The example object is achieved by a method and/or a computer programmingproduct for carrying out the method using a computer, in which during aprogram run, for each allocation of a memory region at least oneinformation item concerning the performed allocation is entered in anallocation list. A check is made as to whether the allocation listcontains a stored reference pattern of information that is typical forone or more memory leaks, and after a stored pattern is found theprogram run is paused, or a memory leak thus detected is associated withthe region of the running program whose processing resulted in the mostrecent entry in the allocation list.

One concept of the invention is that at least one reference pattern ispresent which contains a sequence of determined information that isknown for a memory leak resulting from a running program, whose site oforigin in the program is to be determined in order to eliminate theerrors which led to creation of the memory leak.

Thus, according to one aspect of the invention, during the run time ofthe program a search is made as to whether an information sequence hasbeen generated in the allocation list, supplemented during the run timewith at least one information item with each new allocation of memory,which corresponds to the stored pattern. If such a stored referencepattern is found in the allocation list, this indicates that the soughtmemory leak has occurred in the program, and in particular the time ofoccurrence is specified by the time that the most recent allocationinformation was written in the allocation list. Thus, for an accuratetemporal resolution of the occurrence and localization in program codeit is advantageous when the search for a stored reference pattern isstarted anew each time after information is written in the allocationlist.

Since this search is conducted during the run time of the program, it ispossible for the program to immediately pause when the reference patternbeing searched for has been found. The programmer thus receivesinformation about the location of the origin of a memory leak in theprogram code and can eliminate the error.

As an alternative, it is possible that the program is not paused, butinstead a memory leak thus detected is associated with the region of therunning program whose processing resulted in the most recent entry inthe allocation list. For example, an association table may be generatedin this manner, and at a later time the programmer may identify theparts of the program responsible for the error by use of the associationinformation.

Compared to the prior art, this aspect of the invention thus offers theadvantage that, in addition to a determination that a memory leak hasoccurred, it is also possible to localize in the program the programcode responsible for the error.

It is thus an aspect of the invention that, in addition to the programto be investigated, a program routine is also processed by a computerwhich logs the allocation of memory and ensures that for the allocation,typical and/or meaningful information is always entered in theallocation list when a new allocation takes place.

Such a routine may be provided, for example, in a software library whichis linked to the program, for example, so that the routine may be calledup with each allocation.

Typical, important, or meaningful information concerning a performedallocation may, for example, be built from the length of an allocatedmemory region. Thus, the allocation list may be formed by a list inwhich numbers corresponding to the length of the respective memoryregion most recently allocated are continuously entered in succession.The location of the numbers in the list provides information which isalso used to automatically identify the relative distances of therespectively allocated memory blocks from one another.

The at least one reference pattern stored for use in a comparison may becreated in any manner. For example, it may constitute a librarycontaining typical patterns which, for example, result from typicalprogramming errors.

In certain example embodiments of the method according to certainaspects of the invention, preceding program runs may be performed beforea program run for localization of a program code creating a memory leak.This provides an overview of the type of memory leaks the program to beinvestigated creates as a whole, and the types of patterns that aretypical for the memory leak, so that later the localization may beperformed during the run time of a separate program run. Programs knownin the prior art for generating memory leak lists may be used for thispurpose.

In one embodiment, for creating at least one reference pattern, inparticular for a preceding program run, a memory leak list may begenerated which after the program run contains information concerningall memory leaks originating during the program run, whereby the memoryleak list or a file created therefrom is searched for information thatis typical for memory leaks, and this information or data derivedtherefrom is stored as at least one pattern.

Absolute allocation numbers and memory region lengths as describedabove, for example, may be recorded in such memory leak lists. It isthus possible to generate reference patterns from such a memory leaklist, for example by searching a memory leak list for the occurrence oflength indications and/or allocation numbers. One or more consecutivelength indications may form a reference pattern which is stored forsubsequent localization, for example by storing the sequence orsubsequence of the length indication listed in the memory leak list.

It is problematic that, possibly due to influences from the operatingsystem or other programs, an absolute sequence of length indications insuch a memory leak list is not always the same, so that a stored patternmay not necessarily be found in a subsequent program run.

Thus, in another example embodiment for creating at least one referencepattern for at least two, for example, preceding, program runs onerespective memory leak list is generated which after the particularprogram run includes information concerning all memory leaks originatingin the particular program run, whereby the at least two memory leaklists or files produced therefrom are searched, at least in places, formatching information. The information or data derived therefrom whichmatches at least in places is stored as at least one pattern, and inparticular each contiguous region of matching information forms apattern.

Thus, a program to be investigated for programming errors is run atleast twice. In each program run, a memory leak list is generated, forexample, by use of a prescribed method known and offered by Microsoft,or by use of another method which provides such a memory leak list.

According to this aspect of the invention, the at least two memory leaklists or files produced therefrom for the respective program runs arethen searched for matching patterns.

The occurrence of a common pattern in both memory leak lists/files mayindicate that a memory leak has occurred, for example, when expandeddeterminability is established via the pattern and it is thus madepossible to find the underlying programming error.

One concept of this embodiment is that searching for matching patternsin the at least two memory leak lists or data generated therefromincreases the likelihood that, by means of a detected pattern whichindicates a memory leak, such a memory leak is identified which isattributed to the run of the program being investigated, and not toother circumstances.

As previously mentioned, in the evaluation of an individual memory leaklist it is problematic that, in addition to memory leaks created by theprogram to be investigated, memory leaks are also listed which mayresult from influences by programs or operating system routines runningin parallel which are more or less coincidental, i.e., are notdeterministically arranged in the sequence of the detected memory leakand are not of interest to the programmer.

Since it is unlikely that for at least one additional program run, amemory leak, for example, at the same location and having the samelength, in turn is “coincidentally” created by another program/operatingsystem, and the memory leaks which are definitively attributed to theprogram being investigated, even for different/multiple program runs,produce at least partly identical information in a memory leak list,such as the length and location of the leak, or the distance from apreviously created leak, when the same information appears in the atleast two memory leak lists or data generated therefrom, a conclusioncan be drawn that a memory leak identified in this manner is attributedto a programming error in the program being investigated, and not toanother program running in parallel, or to the operating system.

In order to find the matching information in the respective memory leaklists, a method may be used for a pattern search of the respective listsor of files which at least partially contain information concerning therespective memory leak lists, or possibly also newly generatedinformation.

Thus, known methods may be used for the pattern search which do notconstitute the actual subject matter of the invention. For example,methods known to one skilled in the art, such as the longest commonsubsequence (LCS) algorithm or the diff algorithm, may be used which areable to identify patterns based, for example, on recognition of thelongest contiguous character sequence. The software program BeyondCompare, known to one skilled in the art, may also be used.

Such methods for pattern recognition may be implemented in a separateprogram which reads the information from the memory leak lists or thefiles produced therefrom, or may already be implemented in a programwhich completely carries out the method according to the invention.

Thus, such a complete program may be started on a computer by thedeveloper, for example, whereby as a delivery parameter, for example,the name of the program to be investigated may be delivered, or theprogram code may be delivered directly. The program for carrying out themethod according to the invention may then perform the at least two-timeexecution and generate the lists or files from the lists, and, forexample, perform the pattern recognition, immediately, for example.

To simplify the search for matching patterns, in one embodiment of theinvention the length of the allocated and no longer released memoryblocks and/or the distance of a memory leak from a previous memory leakmay be investigated. To this end, this information may also be extractedfrom the memory leak lists, and in particular written in separate filesbefore a pattern search.

An essential concept is that memory leaks which are created by a programto be investigated are presumed to always have the same length, and maytherefore be associated with the program. Since this may also occur foroperating system routines that are periodically called up, according toone example embodiment, the location of a memory leak may also beevaluated, or, as previously mentioned, since this location may bedifferent even for two identical program runs, the distance between twomemory leaks may be evaluated, since these remain constant for twoidentical program runs.

It may therefore be advantageous to base the pattern search primarily onthe distance and length of memory leaks. Entries may be disregarded inthe pattern search in which a distance exceeds a specified limit value,for example, when the distance is greater than 100.

To simplify this search, in one example embodiment of the inventioncertain information may first be written from a particular memory leaklist to a respective separate file, and information may optionally begenerated anew from the existing information. The information which isextracted from the particular memory leak list may constitute, forexample, at least the distances and lengths of memory leaks, whereby,for example, the distances may be generated or determined from thedifference in the allocation numbers which are written in the listsduring generation of the memory leak lists by use of the known methods.

The search for such patterns referenced above is thus simplified whenthe separate files that are investigated primarily contain informationwhich may possibly be provided first, such as the difference in theallocation numbers, so that in turn the pattern recognition methods ofthe aforementioned type may then be used in a simplified manner, which,for example, recognize the largest text regions in agreement, andtherefore do not also have to be designed for searching for distancesand lengths of memory leaks or for other specified patterns.

Standard methods may thus be used. However, generation of suchintermediately placed files is not absolutely necessary for the method;the matching patterns may also be searched directly in the memory leaklists, optionally using programs adapted for this purpose.

According to one embodiment of the method, recurring number pairs, forexample, composed of the leak distance and leak length, and possiblycontaining information about where the number pairs have been found in afile or an original memory leak list, are used as patterns. Theselocation indications may be provided by line numbers.

When matching information is found while carrying out the methodaccording to one aspect of the invention, it is advantageous to storesuch matching information as reference patterns for later access in thelocalization.

Regardless of their location of origin, reference patterns may be storedin a memory region of the computer on which the program to beinvestigated or a program for carrying out the method runs. For example,the storage may occur in the registry of the computer. It isadvantageous when only patterns containing more than one memory leak arestored for later comparison, since with an increasing number ofsuccessive memory leaks there is a higher likelihood that these memoryleaks are created by the program to be investigated.

By use of the reference patterns obtained in this manner or in someother way, the programmer is provided with better options foridentifying memory leaks, for which it is possible to make an assignmentto the programming regions that are responsible for the memory leak.

By use of the reference patterns, optionally obtained beforehand, oneprogram run may then be carried out for at least one reference pattern,or, for example, for each individual reference pattern, and at the sametime a previously described allocation list is generated in which aftereach new entry a search is made for the particular reference pattern.

It may happen that a pattern stored in the allocation list is found in aprogram run, but in fact no memory leak has occurred. Thus, afterfinding a pattern it is possible that a conclusion can be made only asto the existence of an actual memory leak, when in fact a memory leakhas also been entered at the same time in a memory leak list maintainedin parallel.

If a match is found, for example, for a simultaneous entry of a memoryleak in the memory leak list, the run of the program being investigatedmay be paused, or at a minimum the association described above may beperformed.

It is thus possible to determine not only that a memory leak is present,but also by pausing the program execution at the instant that a memoryleak is found, it is possible to determine the run time point or thelocation in the run program at which the memory leak originated. Thus,according to the invention a programmer has a very simple option, inaddition to determining a memory leak, to also localize the memory leakand eliminate the error in the programming.

By use of the method according to the invention, a found memory leak maythus be associated with a region of a run program by pausing the programexecution or in some other manner, for example by tracing or tracking.

In addition to the possibility of pausing the program when a memory leakis determined for a found pattern, in an alternative or cumulativemanner it is possible to store an association of the found memory leakwith a program region where the error originated. Thus, in thisembodiment the program may still be run, even when the programmer hasthe option to find the errors in the program by use of such anassociation list.

BRIEF DESCRIPTION OF THE DRAWINGS

One exemplary embodiment is described in greater detail below withreference to the figures, which show the following:

FIG. 1 shows an illustration of the method as a flow diagram;

FIG. 2 shows an excerpt from a memory leak list from Microsoft, forexample;

FIG. 3 shows information from a line in the memory leak list;

FIG. 4 shows a comparison of two memory leaks converted to standardfiles;

FIG. 5: shows the recognized memory leak patterns following thedifferentiation unit; and

FIG. 6 a-6 c: shows the description of the search for stored referencepatterns.

DETAILED DESCRIPTION

The starting point for the method according to one aspect of theinvention, illustrated here by way of example according to FIG. 1, istwo program runs 101 in the programmed software of the developer whichare to be investigated for whether, as the result of programming error,the program runs reserve memory which is not released after use. The twoprogram runs are schematically illustrated in a single box 101.

In each of the two program runs a memory leak list 103 a or 103 b isgenerated by the Microsoft Visual Studio development environment or byanother program which may run on the computer in parallel with theprogram run, and the memory leak list logs all memory leaks createdduring the program run without providing information from which thelocation of origin in the program may be determined.

FIG. 2 shows an example of an excerpt from such a list 103 a or 103 b.Such a memory leak list may contain a large amount of information, suchas the information 201, which in the extract shown in FIG. 3 providesdata concerning the file name 301, line number 302, allocation number303, memory address 304, and memory block size 305.

At this point it should be noted that other output information may beused, whereby for the method according to the invention a relativeindication of the position or the distance from a preceding memory leakis used as the location of the memory leak by way of example, and thememory leak in this case may be read from the allocation number bytaking the difference between two consecutive allocation numbers.Furthermore, according to the invention the size of the memory leak isused, which is provided directly from the list 103 a or 103 b by alength indication 305 and which may be read, for example, as plain text.

From a particular memory leak list 103 a/b, by use of a program 104 a or104 b, for example, which may run on the same computer and which in oneexample runs as a readout script 104 a/b (provided in the appendix), thecontents of each memory leak list 103 a or 103 b may be converted to astandard format, for example, or may be extracted into a respective newfile 105 a/105 b in which the characteristic information, which includesthe position with respect to the preceding memory leak and the storagesize of the memory leak, is stored.

The contents of possible files 105 a/b are illustrated in FIG. 4. As anexample, in each file the information is illustrated as a tuple inbraces. The first entry in the tuple specifies the positioncorresponding to the distance from the preceding memory leak, and thesecond entry specifies the size of the memory leak, each line containinga new memory leak entry. The two columns 401 and 402 are excerpts fromthe respective files 105 a and 105 b which originate from the twoidentical program runs 101.

As described, two identical program runs 101 do not result in identicalmemory leak lists, in particular for large, graphical user interface(GUI)-intensive programs. This is due in part to the fact that duringprogram run 101 the operating system automatically executes system callsand interrupts at times that are not predictable in advance. Toeliminate these influences and to determine the effective memory leaks,at least two identical program runs 101 are carried out for which therespective memory leak list 103 a/b is determined (a indicates the firstrun, and b, the second run).

From the memory leak lists 103 a/b in each case the file 105 a/b isdetermined via the readout script 104 a/b. The information concerningmemory leaks is contained in the respective standard files 105 a/b, andalthough the information has a recurring information pattern as a resultof its origin, it does not always occur at the same positions in thefile.

To produce reference patterns for subsequent localization during aprogram run, the files 105 a/b are sent to a differential unit 107. Thedifferential unit 107 is implemented, for example, by software which mayrun on the same computer and which contains, for example, the programmedconversion of the longest common subsequence (LCS) algorithm or the diffalgorithm, which are able to identify patterns based, for example, onrecognition of the longest contiguous character sequence.

FIG. 5 shows an example excerpt of the output from a differential unit107 which has converted the Beyond Compare algorithm. Columns 501 and502 identify the line numbers of files 105 a and 105 b for whichmatching tuples have been found. The horizontal dashed lines 503separate corresponding matching sections which thus identify a memoryleak pattern which may be used as a reference pattern. In addition, therelative positions and the sizes of the memory leaks are indicated bythe tuples, analogously to FIG. 4.

An examination of FIG. 4 reveals that the tuple values of {0, 48} matchin line 1 of the entry in both files 105 a and b. This information isrecognized as a pattern, and as shown in FIG. 5 is stored as 1, 1, {0,48}. There is no agreement in the second line of FIG. 4. The nextagreement occurs in lines 3 and 4 of FIG. 4, with the tuple values of{56, 54} and {388, 46}, respectively. By means of this comparativesearch the list or file according to FIG. 5 is successively generated,only one excerpt being shown in FIG. 5 as an example.

An additional recognized pattern is indicated by reference numeral 505,for example. This pattern comprises three entries as a further possiblecontiguous agreement between files 105 a and 105 b. This is followed bya pattern containing four entries, followed by a pattern containing onlyone entry.

For effective further use, the results from the differential unit 107may be adjusted for individual entries, such as entry 504, whichcorresponds to a memory leak pattern containing one entry, and may beadjusted for entries that are a great distance from the preceding entry,such as in the fourth and thirteenth lines in FIG. 4, although in thiscase there is agreement, for which in particular a separate unit 109 maybe provided.

In another example embodiment, the contributions of tuples havingdistances >100 are disregarded for the pattern, since thesecontributions presumably are not a factor in the pattern for the samereason as for the other memory leaks. Accordingly, entries with suchexcessively large distances are not listed in FIG. 5.

The remaining memory leak patterns are successively entered, for examplein the registry file 111, as subsequent reference patterns forindividual program runs. An additional program run 113 is then carriedout, and the stored reference patterns are searched and evaluated duringthe run time.

The sequence of the memory requirements occurring in the program run iscompared to that stored in the registry and read from that location uponprogram startup, and is logged, for example, in the allocation list 115.The information in the allocation list may be recorded in a debug outputwhich contains all information that is internally generated during aprogram run. The entire debug output thus contains informationconcerning the particular pattern for which a memory leak occurred.

In one example, a logged memory leak may have actually occurred duringthe eighth pattern recognition. This information in turn may be written117 in the registry file 119, and upon recurrence (the eighth occurrenceof the pattern corresponds to a memory leak) the new program run 121 ispaused and a branch is made to the corresponding source text 123(programming region) which corresponds to the insertion of a break pointin the registry.

Description of the Pattern Search

In the search for the locations in the program at which a memory leakoriginates, a key component is the pausing of the program execution atthe moment at which an allocation is performed which fits the specifiedpattern (whatever its origin).

For this purpose, a service routine is registered, in particular at theelementary run time libraries for the programming environment (in thepresent embodiment, Microsoft Visual C++ together with its CRT library),during a program run, and the service routine is then called up for eachmemory allocation, and as an argument receives at least the requiredmemory block size. These required memory block sizes or lengths areconsecutively entered in an allocation list.

The reference patterns to be searched for may comprise a sequence ofmemory allocations, represented by number pairs, the first numberrepresenting the distance from the preceding allocation and the secondnumber representing the required memory block size. As previouslydescribed, the patterns may be generated by at least two consecutivelyexecuted program runs.

These pairs may then be converted to a linear list of individual values,a pattern list, by the fact that the fields are filled with the memoryblock sizes at the correct distances, and the intermediate fieldscontain a zero. FIG. 6 a shows such a pattern list.

During the program run the occurring memory allocations are logged in anallocation list, in particular whereby for logical reasons it is nolonger necessary for these memory allocations to be longer than thepattern lists. At that location the allocations are recorded, inparticular by entering the most recent allocation at the front end andmoving all preceding allocations one position to the right. Such anallocation list is shown in FIG. 6 b.

The allocation list is compared to the pattern list after eachallocation and entry into the allocation list. Only fields areconsidered which are not equal to zero in the pattern list. This isshown in FIG. 6 c, in which the agreements are shown in shaded form.

When the field contents of the upper pattern list and the lowerallocation list match (as illustrated), the pattern has beensuccessfully recognized. In this case the program run may be paused, andthe programmer then receives information concerning the location wherethe error originated.

The following table provides a source code listing of a program inaccordance with one embodiment of the disclosed system.

TABLE A Imports System Imports EnvDTE Imports EnvDTE80 ImportsMicrosoft.Win32 Imports System.Diagnostics ImportsSystem.Collections.Generic Imports System.Text.RegularExpressionsImports System.Windows.Forms Public Module MemoryLeaks   FunctionMakeHexStr(ByVal Number, ByRef Count)     Dim HexString As String    Dim i As Integer = 0     For i = 0 To 3       Dim ByteVal As Integer= Number Mod 256       Dim HexDigit As String = Hex(ByteVal)       IfLen(HexDigit) = 1 Then         HexDigit = “0” + HexDigit       End If      HexString = HexString + HexDigit + “,”       Number = (Number −ByteVal) / 256     Next     Count = Count + 1     If Count Mod 4 = 0Then       HexString = HexString + “\” + vbCrLf + “  ”     End If    MakeHexStr = HexString   End Function   FunctionExtractLeakPatterns( ) As String     Dim PatternText As String     DimMemLeakDump As TextDocument =DTE.ToolWindows.OutputWindow.ActivePane.TextDocument    MemLeakDump.Selection.StartOfDocument( )     IfMemLeakDump.Selection.FindText(“memory leaks”) Then       Dim oRe AsRegex       Dim base As Integer = 0       Dim lastLine As Integer = 0      Do While MemLeakDump.Selection.FindText(“bytes long”)         ‘ ifthe current line is less than the previous, we passed the end of thefile!         If MemLeakDump.Selection.CurrentLine <= lastLine Then          Exit Do         Else           ‘ remember line number ofcurrent occureece           lastLine = MemLeakDump.Selection.CurrentLine        End If         ‘ select the whole line        MemLeakDump.Selection.SelectLine( )         Dim lineText AsString = MemLeakDump.Selection.Text         oRe = NewRegex(“.*{([0-9]+)}.* ([0-9]+) bytes.*”)         IfoRe.IsMatch(lineText) Then           Dim AllocText As String =oRe.Replace(lineText, “$1”)           Dim SizeText As String =oRe.Replace(lineText, “$2”)           If base = 0 Then             base= CLng(AllocText)           End If           Dim AllocNum As Integer =base − CLng(AllocText)           If AllocNum < 0 Then             ExitDo           End If           PatternText = PatternText + “{” +Format(AllocNum) + “,” + Format(Val(SizeText)) + “}” + vbCrLf          base = CLng(AllocText)         End If       Loop     End If    ExtractLeakPatterns = PatternText   End Function   SubBuildMemLeakPattern( )     ‘DESCRIPTION: Creates a memory leak matchpattern from a selected portion of debug output text     ‘ Create a newtext document.     DTE.ItemOperations.NewFile(“General\Text File”,“MemLeakPattern”)     ActiveDocument.Selection.Text =ExtractLeakPatterns( )   End Sub   Sub BuildMemLeakPatternFile( )    Dim PatternText As String = ActiveDocument.Selection.Text     DimRegFileText As String     Dim NumCount As Integer = 0     Dim oRe AsRegex     oRe = New Regex(“{([0-9]+),([0-9]+)}”)     Dim AllMatches AsMatch = oRe.Match(PatternText)     Do While AllMatches.Length > 0      Dim CurrMatch As String = AllMatches.Value       Dim AllocNum AsInteger = oRe.Replace(CurrMatch, “$1”)       If NumCount = 0 Then        AllocNum = 0       End If       Dim SizeNum As Integer =oRe.Replace(CurrMatch, “$2”)       Dim j As Integer       For j = 2 ToAllocNum         RegFileText = RegFileText + MakeHexStr(0, NumCount)      Next       RegFileText = RegFileText + MakeHexStr(SizeNum,NumCount)       AllMatches = AllMatches.NextMatch     Loop     ‘ Createa new text document.     DTE.ItemOperations.NewFile(“General\Text File”,“MemLeakPattern.reg”)     If NumCount = 0 Then      ActiveDocument.Selection.Text = “No valid memory leak patternsselected”     Elself RegFileText.Length > 3000 Then      ActiveDocument.Selection.Text = “Memory leak patterns too large”    Else       Dim CountText As String = MakeHexStr(NumCount, NumCount)      ‘ create appropriate .reg file       ActiveDocument.Selection.Text= _(—)         “REGEDIT4” + vbCrLf + vbCrLf _(—)       +“[HKEY_CURRENT_USER\Software\dSPACE\CalDesk\MemLeakTracking]” + vbCrLf_(—)       + “”“Enable”“=dword:00000001” + vbCrLf _(—)       +“”“Pattern”“=hex:” + CountText + RegFileText + “00” + vbCrLf _(—)      + “”“BreakAtMatchNo”“=dword:00000000” + vbCrLf _(—)       +“”“HideLeaksUntilMatch”“=dword:00000000” + vbCrLf _(—)       +“”“HideLeaksAfterMatch”“=dword:00000000” + vbCrLf     End If   End Sub  Sub CheckMemLeakHits( )     Dim mDict As SortedDictionary(Of Integer,Integer) = New SortedDictionary(Of Integer, Integer)     Dim oRe AsRegex = New Regex(“matches \( *([0-9]+)\)[ a-z]+([0-9]+)”)     DimMemLeakDump As TextDocument =DTE.ToolWindows.OutputWindow.ActivePane.TextDocument    MemLeakDump.Selection.StartOfDocument( )     Do WhileMemLeakDump.Selection.FindText(“*** Condition matches”)      MemLeakDump.Selection.SelectLine( )       Dim TheMatch As Match =oRe.Match(MemLeakDump.Selection.Text)       If TheMatch.Length > 0 Then        Dim CurrMatch As String = TheMatch.Value         Dim MatchNum AsInteger = oRe.Replace(CurrMatch, “$1”)         Dim AllocNum As Integer =oRe.Replace(CurrMatch, “$2”)         mDict.Add(AllocNum, MatchNum)      End If     Loop     For Each match As KeyValuePair(Of Integer,Integer) In mDict       MemLeakDump.Selection.StartOfDocument( )      If MemLeakDump.Selection.FindText(“{” + Format(match.Key) + “}”)Then         Dim reg As RegistryKey = Registry.CurrentUser         reg =reg.OpenSubKey(“Software”)         reg = reg.OpenSubKey(“dSPACE”)        reg = reg.OpenSubKey(“CalDesk”)         reg =reg.OpenSubKey(“MemLeakTracking”, True)        reg.SetValue(“BreakAtMatchNo”, match.Value)        MessageBox.Show(“Match number ” + Format(match.Value) + “ isindeed a memory leak and has been activated for debug-break”, “Success”)        Exit For       End If     Next   End Sub End Module

The embodiments described herein are not to be construed as limiting,and in particular may be taken individually or combined as a whole withthe embodiments in the general section of the description.

1-12. (canceled)
 13. A method for detecting memory leaks produced by acomputer program running on a computer comprising, create a first memoryleak list that records memory allocations that were not de-allocatedafter a first run of the computer program, wherein the list records theposition of each such memory allocation and its size; during a secondrun of the computer program create a match list that records memoryallocations matching one or more sequence and size patterns recorded inthe first memory leak list; create a second memory leak list thatrecords memory allocations that were not de-allocated after the secondrun of the computer program, wherein the list records the position ofeach such memory allocation and its size; identify entries on the matchlist that correspond to entries on the second memory leak list; during athird run of the computer program using the match list and identifiedentries to detect the portions of the computer program that created thememory leak.
 14. The method of claim 13 wherein the detection comprisesrecording a source code function that created the detected memory leak.15. The method of claim 13 wherein the detection comprises pausing therunning of the program at the point where the detected memory leak isallocated.
 16. A method for detecting memory leaks produced by acomputer program running on a computer comprising, create a first memoryleak list that records memory allocations that were not de-allocatedafter a first run of the computer program, wherein the list records theposition of each such memory allocation and its size; create a secondmemory leak list that records memory allocations that were notde-allocated after the second run of the computer program, wherein thelist records the position of each such memory allocation and its size;create a stored reference pattern list by identifying consecutiveentries on the first and second memory leak lists that correspond to oneanother; during a third run of the computer program using the storedreference pattern list to detect the portions of the computer programthat created the memory leak.